<template>
  <div class="upload-file">
    <el-upload
        ref="fileUpload"
        :action="state.uploadFileUrl"
        :before-upload="handleBeforeUpload"
        :file-list="state.fileList"
        :headers="state.headers"
        :limit="limit"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        :on-success="handleUploadSuccess"
        :show-file-list="false"
        class="upload-file-uploader"
        multiple
    >
      <!-- 上传按钮 -->
      <el-button size="mini" type="primary">选取文件</el-button>
      <!-- 上传提示 -->
      <template v-slot:tip>
        <div v-if="showTip" class="el-upload__tip">
          请上传
          <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
          <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
          的文件
        </div>
      </template>
    </el-upload>

    <!-- 文件列表 -->
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      <li v-for="(file, index) in state.fileList" :key="file.url"
          class="el-upload-list__item ele-upload-list__item-content">
        <el-link :href="file.url" :underline="false" target="_blank">
          <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" type="danger" @click="handleDelete(index)">删除</el-link>
        </div>
      </li>
    </transition-group>
  </div>
</template>


<script lang="ts" name="FileUpload" setup>

import {computed, reactive, ref, watch} from "vue";
import {ossApi} from "/@/api/sys/oss";
import {ElLoading, ElMessage, UploadInstance} from "element-plus";
import {Session} from "/@/utils/storage";

// 定义子组件向父组件传值/事件
const emit = defineEmits(['update']);

const props = defineProps({
  modelValue: [String, Object, Array],
  // 图片数量限制
  limit: {
    type: Number,
    default: 5,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["doc", "xls", "ppt", "txt", "pdf"],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  }
});

watch(() => props.modelValue, (val) => {
  if (val) {
    let temp = 1;
    // 首先将值转为数组
    let list;
    if (Array.isArray(val)) {
      list = val;
    } else {
      ossApi().listByUrls(val.split(',')).then(res => {
        list = res.data.map((oss: any) => {
          oss = {name: oss.id, url: oss.url, id: oss.id};
          return oss;
        });
        // 然后将数组转为对象数组
        state.fileList = list.map((item: any) => {
          item = {name: item.name, url: item.url, id: item.id};
          item.uid = item.uid || new Date().getTime() + temp++;
          return item;
        });
      })
    }
  } else {
    state.fileList = [];
    return [];
  }
});


const loadingInstance = ref();
const fileUpload = ref<UploadInstance>();
const state = reactive({
  number: 0,
  loadingInstance: {},
  uploadList: [],
  uploadFileUrl: import.meta.env.VITE_API_URL + "/oss/upload", // 上传文件服务器地址
  headers: {
    Authorization: Session.get('token'),
  },
  fileList: [],
})


// 获取布局配置信息
const showTip = computed(() => {
  return props.isShowTip && (props.fileType || props.fileSize);
});

// 上传前校检格式和大小
const handleBeforeUpload = (file: any) => {
  // 校检文件类型
  if (props.fileType) {
    const fileName = file.name.split('.');
    const fileExt = fileName[fileName.length - 1];
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      ElMessage.error(`文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`);
      return false;
    }
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      ElMessage.error(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  loadingInstance.value = ElLoading.service({
    lock: true,
    text: '正在上传文件，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  state.number++;
  return true;
}

// 文件个数超出
const handleExceed = () => {
  ElMessage.error(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传失败
const handleUploadError = () => {
  ElMessage.error("上传文件失败，请重试");
  loadingInstance.value.close();
}

// 上传成功回调
const handleUploadSuccess = (res: any, file: any) => {
  if (res.code === 200) {
    state.uploadList.push(
        {
          name: res.data.fileName,
          url: res.data.url,
          ossId: res.data.id
        }
    );
    uploadedSuccessfully();
  } else {
    state.number--;
    loadingInstance.value.close();
    ElMessage.error(res.msg);
    fileUpload.value!.handleRemove(file);
    uploadedSuccessfully();
  }
}

// 删除文件
const handleDelete = (index: any) => {
  let id = state.fileList[index].id;
  ossApi().delOss({id: id});
  state.fileList.splice(index, 1);
  emit("update:modelValue", listToString(files, ","));
}

// 上传结束处理
const uploadedSuccessfully = () => {
  if (state.number > 0 && state.uploadList.length === state.number) {
    state.fileList = state.fileList.concat(state.uploadList);
    state.uploadList = [];
    state.number = 0;
    emit("update:modelValue", listToString(state.fileList, ","));
    loadingInstance.value.close();
  }
}

// 获取文件名称
const getFileName = (name: any) => {
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return name;
  }
}

// 对象转成指定字符串分隔
const listToString = (list: any, separator: any) => {
  let strs = "";
  separator = separator || ",";
  for (let i in list) {
    strs += list[i].url + separator;
  }
  return strs != "" ? strs.substr(0, strs.length - 1) : "";
}
</script>

<style lang="scss" scoped>
.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
